package com.longg.controller.login;

import com.longg.comm.Comm;
import com.longg.controller.BaseController;
import com.longg.model.User;
import com.longg.service.IUserInfoService;
import com.longg.service.IUserService;
import com.longg.service.impl.UserInfoServiceImpl;
import com.longg.service.impl.UserServiceImpl;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
@WebServlet("/log/*")
public class LoginController extends BaseController {
    private IUserService service = new UserServiceImpl();
    private IUserInfoService userInfoService = new UserInfoServiceImpl();

    public void login(HttpServletRequest req, HttpServletResponse resp)  {
        try {
            HttpSession session = req.getSession();

            String username = req.getParameter("username");
            String password = req.getParameter("password");
            String rememberMe = req.getParameter("rememberMe");

            User user = service.findByName(username);

            if(null != user){
                if(password.equals(user.getPassword())){
                    if("on".equals(rememberMe)){
                        Cookie cookie = new Cookie("uName",username);
                        cookie.setPath("/");
                        cookie.setMaxAge(Comm.COOKIE_MAX_TIME);
                        resp.addCookie(cookie);
                    }
                    Map<String,Object> userInfoMap = service.getUserBaseInfo(username);
                    userInfoService.updateLoginTime(user);
                    String sId = session.getId();
                    session.setAttribute("userInfoMap",userInfoMap);
                    session.setAttribute(sId,userInfoMap.get("id"));
                    resp.sendRedirect(req.getContextPath() + "/assets/html/home.jsp");
                    return;
                }else {
                    session.setAttribute("loginError","密码错误！");
                }
            }else {
                session.setAttribute("loginError","没有该账号！");
            }
            resp.sendRedirect(req.getContextPath() + "/index.jsp");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void checkEmail(HttpServletRequest req, HttpServletResponse resp){
        try {
            String email = req.getParameter("email");
            List<User> userList = service.findByEmail(email);
            if(userList.isEmpty() || null == userList){
                resp.getWriter().write("0");
            }else {
                resp.getWriter().write("1");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void checkUsername(HttpServletRequest req, HttpServletResponse resp){
        try {
            String username = req.getParameter("username");
            User user = service.findByName(username);
            if(null == user){
                resp.getWriter().write("0");
            }else {
                resp.getWriter().write("1");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void register(HttpServletRequest req, HttpServletResponse resp){
        try {
            HttpSession session = req.getSession();

            String email = req.getParameter("form-email");
            String username = req.getParameter("form-username");
            String password = req.getParameter("form-password");
            String password2 = req.getParameter("form-password2");

            List<User> userList = service.findByEmailOrName(email,username);
            if(userList.isEmpty() || null == userList){
                if(password.equals(password2) && null != password && !"".equals(password) && null != password2 && !"".equals(password2)){
                    User user = new User();
                    user.setEmail(email);
                    user.setPassword(password);
                    user.setUsername(username);
                    boolean flag = service.addUser(user);
                    if(flag){
                        userInfoService.register(username,new Date());
                        session.setAttribute("registerMsg","注册成功！");
                        resp.sendRedirect(req.getContextPath() + "/index.jsp");
                        return;
                    }
                    session.setAttribute("registerMsg","注册失败");
                    resp.sendRedirect(req.getContextPath() + "/register.jsp");
                    return;
                }else{
                    session.setAttribute("registerMsg","两次输入密码不一致或为空！");
                }

            }else{
                session.setAttribute("registerMsg","邮箱或账号已被注册！");
            }
            resp.sendRedirect(req.getContextPath() + "/register.jsp");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void sendCode(HttpServletRequest req, HttpServletResponse resp){
        HttpSession session = req.getSession();
        String code = null;
        try {
            String email = req.getParameter("email");
            List<User> userList = service.findByEmail(email);
            if(userList.isEmpty() || null == userList){
                resp.getWriter().write("没有该邮箱!");
                return;
            }
            code = (String) session.getAttribute("code");
            if(null != code){
                resp.getWriter().write("操作频繁!");
                return;
            }
            code = service.sendCode(email);
            session.setAttribute("code",code);
            session.setMaxInactiveInterval(Comm.SESSION_MAX_TIME);
            resp.getWriter().write("发送成功！请注意查收");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void resetPassword(HttpServletRequest req, HttpServletResponse resp){
        HttpSession session = req.getSession();
        String email = req.getParameter("form-email");
        String password = req.getParameter("form-password");
        String code2 = req.getParameter("form-code");
        String code = null;

        try {
            code = (String) session.getAttribute("code");
            if(null == email || "".equals(email) || null == password || "".equals(password) || null == code2 || "".equals(code2)){
                session.setAttribute("resetMsg","信息不能为空！");
                resp.sendRedirect(req.getContextPath() + "/forget.jsp");
                return;
            }else {
                List<User> userList = service.findByEmail(email);
                if(userList.isEmpty() || null == userList){
                    session.setAttribute("resetMsg","没有该邮箱！");
                    resp.sendRedirect(req.getContextPath() + "/forget.jsp");
                }else{
                    if(code == null){
                        session.setAttribute("resetMsg","验证码已失效，请重新发送！");
                        resp.sendRedirect(req.getContextPath() + "/forget.jsp");
                    }else {
                        if(!code.equals(code2)){
                            session.setAttribute("resetMsg","验证码不正确！");
                            resp.sendRedirect(req.getContextPath() + "/forget.jsp");
                        }else{
                            User user = userList.get(0);
                            user.setPassword(password);
                            boolean flag = service.resetPassword(user);
                            if(flag){
                                session.setAttribute("resetMsg","重置成功");
                                resp.sendRedirect(req.getContextPath() + "/index.jsp");
                            }else {
                                session.setAttribute("resetMsg","重置失败！");
                                resp.sendRedirect(req.getContextPath() + "/forget.jsp");
                            }
                        }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void logout(HttpServletRequest req, HttpServletResponse resp){
        try {
            Cookie[] cookies = req.getCookies();
            for(Cookie cookie : cookies){
                if("uName".equals(cookie.getName())){
                    cookie.setMaxAge(0);
                    cookie.setPath("/");
                    resp.addCookie(cookie);
                    req.getSession().removeAttribute("userInfoMap");
                    req.getSession().removeAttribute("infoMap");
                }
            }
            resp.sendRedirect(req.getContextPath() + "/index.jsp");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
